package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/SearchIncome")
public class SearchIncome extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String income = request.getParameter("income");
		String time = request.getParameter("time");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 2019);
		if (income == null)
			income = "Total";
		if (time == null)
			time = "Daily";
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		try {
			Connection con = dbOperator.BasicOperation.getConnection();
			ResultSet rs;
			rs = dbOperator.AdvancedOperation.getIncome(con, income, time);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			int range = 0;
			if(time.equals("Weekly")) {
				while (rs.next()) {
					range = Integer.valueOf(rs.getString(1).substring(5));
					calendar.set(Calendar.WEEK_OF_YEAR, range);
					calendar.set(Calendar.DAY_OF_WEEK, 2);
					Date date1 = calendar.getTime();
					String dateStr1 = sdf.format(date1);
					calendar.set(Calendar.WEEK_OF_YEAR, range+1);
					calendar.set(Calendar.DAY_OF_WEEK, 1);
					Date date2 = calendar.getTime();
					String dateStr2 = sdf.format(date2);
					out.print("<tr>");
					out.println("<td>" + dateStr1 + " to " + dateStr2 + "</td>");
					out.println("<td>" + rs.getDouble(2) + "</td>");
					out.print("</tr>");
				}
			}
			else {
			while (rs.next()) {
				out.print("<tr>");
				out.println("<td>" + rs.getString(1) + "</td>");
				out.println("<td>" + rs.getDouble(2) + "</td>");
				out.print("</tr>");
			}
			}
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
